<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';

const dateRange = ref([]);
const durationChartRef = ref(null);
const qualityChartRef = ref(null);
const avgDuration = ref(7.2);
const deepSleepPercent = ref(28);
const sleepScore = ref(82);

const initCharts = () => {
  // 睡眠时长图表
  const durationChart = echarts.init(durationChartRef.value);
  durationChart.setOption({
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>时长: {c}小时'
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value',
      name: '小时'
    },
    series: [{
      data: [6.5, 7.2, 6.8, 7.5, 7.0, 8.2, 7.8],
      type: 'bar',
      barWidth: '60%',
      itemStyle: {
        color: '#67C23A'
      }
    }]
  });

  // 睡眠质量图表
  const qualityChart = echarts.init(qualityChartRef.value);
  qualityChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}小时 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [{
      name: '睡眠构成',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: true
        }
      },
      data: [
        { value: 2.0, name: '深睡' },
        { value: 4.0, name: '浅睡' },
        { value: 1.2, name: '清醒' }
      ],
      itemStyle: {
        borderRadius: 5,
        borderColor: '#fff',
        borderWidth: 2
      }
    }]
  });

  window.addEventListener('resize', () => {
    durationChart.resize();
    qualityChart.resize();
  });
};

const fetchData = () => {
  console.log('获取睡眠数据，日期范围:', dateRange.value);
};

onMounted(() => {
  initCharts();
  fetchData();
});
</script>

<template>
  <div class="sleep-analysis-container">
    <div class="header">
      <h3>睡眠分析</h3>
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          @change="fetchData"
      />
    </div>

    <div class="charts">
      <div ref="durationChartRef" class="chart" />
      <div ref="qualityChartRef" class="chart" />
    </div>

    <div class="stats">
      <el-statistic title="平均睡眠时长" :value="avgDuration" suffix="小时" />
      <el-statistic title="深睡比例" :value="deepSleepPercent" suffix="%" />
      <el-statistic title="睡眠评分" :value="sleepScore" />
    </div>
  </div>
</template>

<style scoped>
.sleep-analysis-container {
  padding: 15px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.charts {
  display: flex;
  gap: 20px;
}

.chart {
  flex: 1;
  height: 300px;
}

.stats {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
}
</style>